<template>
  <view>
    <!-- 顶部导航组件 -->
    <trace-info v-model:current="currentTabIndex"></trace-info>
    <view class="box">
      <!-- 加载中状态显示 -->
      <uv-loading mode="circle" v-if="loading"></uv-loading>
      <template v-else>
        <!-- 活跃度部分 -->
        <view class="activity-section">
          <view class="activity-title">活跃度</view>
          <view class="activity-status">
            <text class="activity-text" :style="{color: moodInfo.color}">{{ moodInfo.text }}</text>
            <image src="@/static/imgs/huoyue.png" class="activity-medal" />
          </view>
        </view>

        <!-- 健康指标部分 -->
        <view class="health-metrics-section">
          <view class="metrics-title">健康指标</view>
          <view class="metrics-container">
            <view class="metric-item">
              <view class="metric-label">今日运动量</view>
              <view class="metric-value-circle">
                <qiun-data-charts
                  type="arcbar"
                  :opts="motionOpts"
                  :chartData="daysportData"
                />
                <text 
                  v-if="daysportData.value && 
                        daysportData.value.series && 
                        daysportData.value.series.length > 0" 
                  class="metric-value"
                >
                  {{ daysportData.value.series[0].custom }}
                </text>
              </view>
            </view>
            <view class="metric-item">
              <view class="metric-label">当前体温</view>
              <view class="metric-value-circle">
                <qiun-data-charts
                  type="arcbar"
                  :opts="tempOpts"
                  :chartData="TData"
                />
                <text 
                  v-if="TData.value && 
                        TData.value.series && 
                        TData.value.series.length > 0" 
                  class="metric-value"
                >
                  {{ TData.value.series[0].custom }}℃
                </text>
              </view>
            </view>
          </view>
        </view>

        <!-- 运动量趋势部分 -->
        <view class="trend-section">
          <view class="trend-title">运动量</view>
          <view class="trend-tab-container">
            <view 
              class="trend-tab" 
              :class="{ 'active-tab': exerciseTimeRange === 'week' }"
              @click="changeExerciseTimeRange('week')"
            >
              一周内
            </view>
            <view 
              class="trend-tab" 
              :class="{ 'active-tab': exerciseTimeRange ==='month' }"
              @click="changeExerciseTimeRange('month')"
            >
              一月内
            </view>
            <view 
              class="trend-tab" 
              :class="{ 'active-tab': exerciseTimeRange === 'year' }"
              @click="changeExerciseTimeRange('year')"
            >
              一年内
            </view>
          </view>
          <view class="trend-chart-container">
            <qiun-data-charts
              type="line"
              :opts="lineOpts"
              :chartData="chartData"
            />
          </view>
        </view>

        <!-- 体温趋势部分 -->
        <view class="trend-section">
          <view class="trend-title">体温</view>
          <view class="trend-tab-container">
            <view 
              class="trend-tab" 
              :class="{ 'active-tab': temperatureTimeRange === 'week' }"
              @click="changeTemperatureTimeRange('week')"
            >
              一周内
            </view>
            <view 
              class="trend-tab" 
              :class="{ 'active-tab': temperatureTimeRange ==='month' }"
              @click="changeTemperatureTimeRange('month')"
            >
              一月内
            </view>
            <view 
              class="trend-tab" 
              :class="{ 'active-tab': temperatureTimeRange === 'year' }"
              @click="changeTemperatureTimeRange('year')"
            >
              一年内
            </view>
          </view>
          <view class="trend-chart-container">
            <qiun-data-charts
              type="line"
              :opts="temperatureLineOpts"
              :chartData="temperatureLineData"
            />
          </view>
        </view>
      </template>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, reactive, watchEffect } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import qiunDataCharts from '@/uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue';

// 时间范围控制
const exerciseTimeRange = ref('week')
const temperatureTimeRange = ref('week')

// 页面状态
const liveId = ref('')
const loading = ref(true)
const currentTabIndex = ref(0)

// 状态映射
const statusMap = {
  mood: { 1: '正常', 2: '活跃', 3: '欠佳' },
  temperature: { 1: '正常', 2: '偏高', 3: '偏低' }
}

// 图表数据（预初始化嵌套结构）
const daysportData = ref({ value: { series: [] } })
const TData = ref({ value: { series: [] } })
// 初始化series为包含对象的数组，避免后续data属性赋值报错
const chartData = ref({ categories: [], series: [{ name: '步数趋势', data: [] }] }) 
const temperatureLineData = ref({ categories: [], series: [{ name: '体温趋势', data: [] }] }) 

// 图表配置
const motionOpts = ref({
  color: ["#2fc25b"],
  padding: undefined,
  subtitle: { name: '', fontSize: 28, color: "#666666" },
  title: { name: "", fontSize: 0, color: "#737373" },
  extra: {
    arcbar: {
      type: "circle",
      width: 8, // 调整环形宽度
      backgroundColor: "#E9E9E9",
      startAngle: 0,
      endAngle: 2 * Math.PI,
      gap: 0,
      lineCap: "round"
    }
  }
})

const tempOpts = ref({
 ...motionOpts.value,
  color: ["#FF5722"]
})

const lineOpts = ref({
  color: ["#1890FF"],
  padding: [15, 10, 0, 15],
  enableScroll: false,
  legend: { show: false },
  xAxis: { disableGrid: true },
  yAxis: { gridType: "dash", dashLength: 2 },
  extra: { line: { type: "curve", width: 2, activeType: "hollow" } }
})

const temperatureLineOpts = ref({
 ...lineOpts.value,
  color: ["#FF5722"]
})

// 活跃度计算
const moodInfo = computed(() => {
  const status = mockHealthData.xqzt || 1
  return {
    text: statusMap.mood[status] || '正常',
    color: statusMap.mood[status] === '活跃' ? '#ff6600' : 
           statusMap.mood[status] === '欠佳' ? '#ababab' : '#12cc78',
  }
})

// 模拟数据（包含完整结构）
const mockHealthData = reactive({
  xqzt: 2,           // 活跃度状态
  jrbs: 6543,        // 今日步数
  pjtw: 36.8,        // 平均体温（修正为正常范围）
  twzt: 1,           // 体温状态
  trendData: {
    week: { steps: [5000, 6000, 5500, 7000, 6500, 5800, 6200], temp: [36.5, 36.7, 36.6, 36.8, 36.9, 36.7, 36.6] },
    month: { steps: [22000, 25000, 24000, 23000], temp: [36.6, 36.7, 36.5, 36.8] },
    year: { steps: [70000, 68000, 72000, 75000, 73000, 71000, 69000, 74000, 76000, 78000, 77000, 75000], temp: [36.5, 36.6, 36.7, 36.8, 36.9, 37.0, 36.9, 36.8, 36.7, 36.6, 36.5, 36.4] }
  }
})

// 将数据加载逻辑移到 onMounted 钩子中
onMounted(() => {
  loadData()
})

onLoad((options) => {
  liveId.value = options.id || 'mock-123'
})

// 数据加载
const loadData = async () => {
  try {
    updateCharts()
  } catch (error) {
    console.error('数据加载失败:', error)
    uni.showToast({ title: '加载失败，请重试', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateCharts = () => {
  // 今日运动量
  const maxMotion = 100000;
  const motionPercent = (mockHealthData.jrbs / maxMotion) * 100;
  daysportData.value = {
    value: {
      series: [{
        name: '今日步数',
        data: motionPercent,
        custom: mockHealthData.jrbs,
        color: '#2fc25b'
      }]
    }
  }
  motionOpts.value.subtitle.name = `${mockHealthData.jrbs}步`;

  // 当前体温
  const minTemp = 36;
  const maxTemp = 37.5;
  const tempPercent = ((mockHealthData.pjtw - minTemp) / (maxTemp - minTemp)) * 100;
  TData.value = {
    value: {
      series: [{
        name: '当前体温',
        data: tempPercent,
        custom: mockHealthData.pjtw.toFixed(1),
        color: getTempColor(mockHealthData.twzt)
      }]
    }
  }
  tempOpts.value.subtitle.name = `${mockHealthData.pjtw.toFixed(1)}℃`;

  // 运动量趋势
  chartData.value.categories = getTimeLabels(exerciseTimeRange.value);
  chartData.value.series[0].data = getTrendData(exerciseTimeRange.value,'steps');

  // 体温趋势
  temperatureLineData.value.categories = getTimeLabels(temperatureTimeRange.value);
  temperatureLineData.value.series[0].data = getTrendData(temperatureTimeRange.value, 'temp');
}

// 获取趋势数据
const getTrendData = (range, type) => {
  const data = mockHealthData.trendData[range]
  return data? data[type] : []
}

// 获取体温颜色
const getTempColor = (status) => {
  return status === 1? '#2fc25b' : status === 2? '#ff6600' : '#ababab'
}

// 获取时间标签
const getTimeLabels = (range) => {
  switch(range) {
    case 'week': return ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    case'month': return ['第1周', '第2周', '第3周', '第4周']
    case 'year': return ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    default: return []
  }
}

// 时间范围切换
const changeExerciseTimeRange = (range) => {
  exerciseTimeRange.value = range
  updateCharts()
}

const changeTemperatureTimeRange = (range) => {
  temperatureTimeRange.value = range
  updateCharts()
}
</script>

<style scoped>
.box {
  padding: 30rpx 20rpx;
  background-color: #f0f0f0;
}

.activity-section,
.health-metrics-section,
.trend-section {
  margin-bottom: 30rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.activity-title,
.metrics-title,
.trend-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
}

.activity-status {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.activity-text {
  font-size: 40rpx;
  font-weight: 500;
}

.activity-medal {
  width: 80rpx;
  height: 80rpx;
}

.metrics-container {
  display: flex;
  justify-content: space-around;
  gap: 20rpx;
}

.metric-item {
  flex: 1;
  text-align: center;
}

.metric-value-circle {
  width: 180rpx;
  height: 180rpx;
  margin: 0 auto 10rpx;
}

.metric-value {
  font-size: 32rpx;
  color: #666;
}

.trend-tab-container {
  display: flex;
  justify-content: center;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.trend-tab {
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #666;
  background-color: #f0f0f0;
  cursor: pointer;
  transition: all 0.3s;
}

.active-tab {
  background-color: #2fc25b;
  color: #fff;
  box-shadow: 0 2rpx 4rpx rgba(47, 194, 91, 0.2);
}

.trend-chart-container {
  height: 300rpx;
}
</style>